<template>
	<div class="app-container">
		<!-- 搜索条件 -->
		<yd-form class="yd-form-wraper" :options="formOptions" :model="formData" @form-init="formInited" @search="formInited">
			<template #form-btn>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
				<el-button style="margin-left: 15px" type="primary" @click="downloadHandler">下载</el-button>
			</template>
		</yd-form>

		<!-- 业务概况列表 -->
		<YdCard>
			<YdTable
				:formData="formData"
				:tableConfig="tableConfig"
				:tableData="tableData.data"
				@sizeChangeHandler="queryGrid"
				@currentChangeHandler="queryGrid"
				@sortChangeHandler="queryGrid"
			></YdTable>
		</YdCard>
	</div>
</template>

<script setup name="CustomAlarmList" lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getAdvanceAlarm, exportExcel } from '@/api/bpm/alarm/advance_alarm';
import { parseTime } from '@/utils/common';
import { onMounted, ref, reactive, getCurrentInstance, onActivated, computed, watch, nextTick } from 'vue';
import { saveAs } from 'file-saver';
const instance = getCurrentInstance();
const proxy = instance?.proxy;
const route = useRoute();
const router = useRouter();

// 表单配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		prop: 'systemId',
		label: '业务系统',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
		cascaders: [
			{
				cascadersParams: 'segmentIds',
				api: {
					name: 'querySegmentOptions',
				},
			},
		],
	},
	{
		type: 'select',
		prop: 'segmentIds',
		label: '应用节点',
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'alarmLevelIds',
		label: '告警级别',
		api: {
			name: 'queryAlarmLevelOptions',
		},
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'objectTypeIds',
		label: '告警对象',
		api: {
			name: 'queryAlarmObjectOptions',
		},
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'date-picker',
		prop: 'dateRange',
		span: 8,
		dateType: 'datetimerange',
		label: '时间范围',
		enableCrossDay: true,
	},
	{
		type: 'input',
		prop: 'alarmObject',
		label: '告警信息',
	},
]);

// 搜索表单数据
const formData = reactive<FormModelType>({
	objectTypeIds: [''], //告警对象
	alarmLevelIds: [''], //告警级别
	segmentIds: [''], //应用网端
});

// 列表配置
const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警级别',
			prop: 'alarmLevelName',
			width: 100,
			showOverFlowToolTip: true,
		},
		{
			label: '告警时间',
			prop: 'alarmTriggerTime',
			sortable: true,
			width: 170,
		},
		{
			label: '指标',
			prop: 'alarmIndicatorName',
			width: 120,
			showOverFlowToolTip: true,
		},
		{
			label: '告警对象',
			prop: 'objectTypeName',
			width: 120,
			showOverFlowToolTip: true,
		},
		/*{
                    label: '系统',
                    prop: 'systemName'
                },*/
		{
			label: '业务名称',
			prop: 'businessName',
			width: 170,
			showOverFlowToolTip: true,
		},
		{
			label: '应用节点',
			prop: 'segmentName',
			width: 170,
			showOverFlowToolTip: true,
		},
		{
			label: '告警信息',
			prop: 'alarmContext',
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '详情',
					handler: (scope) => {
						handleJumpToDetail(scope.row);
					},
				},
			],
			width: 85,
		},
	],
	pagination: {
		pageNum: 1,
	},
	loading: true,
});
// 列表数据
const tableData = reactive({
	data: [],
	total: 0,
});
const downloadStartTime = ref('');
const downloadEndTime = ref('');
// 下载状态
const downloading = ref(false);
initQuery(route.query, formData);
onActivated(() => {
	formData.systemId = route.query.systemId;
	initQuery(route.query, formData);
});

// 格式化传过来的参数
function initQuery(query: anyObj, formData: FormModelType) {
	try {
		let data = JSON.parse(query.data);
		for (let key in data) {
			formData[key] = data[key];
		}
	} catch {
		for (let key in query) {
			formData[key] = query[key];
		}
	}
}

// 表单初始化完毕
function formInited() {
	initQuery(route.query, formData);
	searchHandler();
}
// 搜索
function searchHandler() {
	formData.pageNum = 1;
	queryGrid();
}

// 去掉空字符串""
function sliceEmptyString(formData: any) {
	let form = JSON.parse(JSON.stringify(formData));
	for (let key in form) {
		if (form[key] instanceof Array) {
			if (form[key].length === 1 && form[key][0] === '') {
				form[key] = [];
			}
		} else {
			if (form[key] === '') {
				delete form[key];
			}
		}
	}
	return form;
}

//查询列表数据
function queryGrid() {
	tableConfig.loading = true;
	downloadStartTime.value = formData.startTime;
	downloadEndTime.value = formData.endTime;
	let params = sliceEmptyString(formData);
	getAdvanceAlarm(params).then((res: ApiResponse) => {
		if (res.code !== 0) {
			tableConfig.loading = false;
			proxy?.$message.warning(res.msg);
			return;
		}
		tableConfig.loading = false;
		tableData.data = res.data.data;
		tableConfig.pagination!.total = res.data.total;
	});
}
// 下载
function downloadHandler() {
	formData.startTime = downloadStartTime.value;
	formData.endTime = downloadEndTime.value;
	downloading.value = true;
	exportExcel(formData).then((res: any) => {
		downloading.value = false;
		const currentDate = new Date();
		const currentDateTimeStr = parseTime(currentDate, '{y}{m}{d}{h}{i}{s}');
		let blob = new Blob([res], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8',
		});
		saveAs(blob, '自定义告警列表_' + currentDateTimeStr + `.xlsx`);
	});
}
// 跳转至相应详情页面
function handleJumpToDetail(row: any) {
	const endTime = new Date(row.alarmTriggerTime).getTime();
	const startTime = parseTime(endTime - row.alarmFrequency * 1000, '{y}-{m}-{d} {h}:{i}:{s}');
	if (!row.objectTypeName) {
		return;
	}
	switch (row.objectTypeName) {
		case '系统':
			router.push({
				path: '/business-monitor/monitor/system-detail/index',
				query: {
					systemId: formData.systemId,
					startTime: startTime,
					endTime: row.alarmTriggerTime,
				},
			});
			break;
		case '业务':
			router.push({
				path: '/business-monitor/monitor/business-detail/index',
				query: {
					systemId: formData.systemId,
					businessCode: row.businessCode,
					startTime: startTime,
					endTime: row.alarmTriggerTime,
				},
			});
			break;
		case '网端':
			router.push({
				path: '/business-monitor/monitor/network-detail/index',
				query: {
					systemId: formData.systemId,
					startTime: startTime,
					endTime: row.alarmTriggerTime,
				},
			});

			break;
	}
}
</script>
<style lang="scss" scoped>
.style-split-yd-card {
	:deep(.el-card) {
		background-color: rgba(29, 39, 75, 0.31);
		border: unset;
		border-radius: 12px;
	}
}
</style>
